package com.cloudcms.web.controller.cms;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cloudcms.web.common.BusinessException;
import com.cloudcms.web.common.Result;
import com.cloudcms.web.util.Uploader;
import com.cloudcms.web.util.Constants;
import com.cloudcms.web.util.PropertyConfig;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/file")
public class UploadController {
	@Autowired
	private PropertyConfig propertyConfig;

	@RequestMapping(value = "/upload/1.0", method = { RequestMethod.GET, RequestMethod.POST })
	public DeferredResult<String> upload(HttpServletRequest request,HttpServletResponse response,MultipartFile upfile) {
		if(upfile == null){
			throw new BusinessException(701L,"请上传文件");
		}
		Result result = new Result();
		long size = upfile.getSize();
		//大小不能够超过100M
		if(size>1024*1024*100){
			throw new BusinessException(701L,"上传文件大小不能超过2M");
		}
		/*if(!upfile.getOriginalFilename().endsWith(".pdf")){
			throw new BusinessException(702L, "只能上传pdf格式的文件");
		}*/

		String bootPath = propertyConfig.getValue("business.upload.rootpath");// 与properties文件中upload.filePath相同
		String visitUrl = Uploader.saveFile(bootPath, upfile,"");

		/*if ("prod".equals(propertyConfig.getValue("spring.profiles.active"))) {
			visitUrl = "/upload/"+Uploader.saveFile(bootPath, upfile,"");
		} else {
			visitUrl = "/upload/"+Uploader.saveFile(bootPath, upfile,"");
		}*/
		Map<String,String> param = new HashMap<String,String>();
		param.put("state", "SUCCESS");
		param.put("url", visitUrl);
		param.put("original", upfile.getOriginalFilename());
		param.put("type", upfile.getContentType());

		param.put("name", upfile.getOriginalFilename());
		param.put("size", String.format("%.2f",  (float)size/1024)+"kb");

		result.put("data",param);
		DeferredResult<String> deferredResult = new DeferredResult<String>(Constants.TIMEOUT_VALUE);
		deferredResult.setResult(result.toString());
		return deferredResult;
	}
}